package org.stvd.repository.common.impl;

import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.stvd.entities.common.AffixUpload;
import org.stvd.repository.base.impl.BaseDaoImpl;
import org.stvd.repository.common.AffixUploadDao;

/**
 * 附件上传Repository实现类
 * @author houzx
 */
@Repository("AffixUploadDao")
public class AffixUploadDaoImpl extends BaseDaoImpl<AffixUpload> implements AffixUploadDao{

    @Override
    @Transactional
    public int updateAffixStatusByAffixIds(String affixIds, String status) {
        String hql = "UPDATE affixUpload SET status = :status, modifyTime=NOW(), remark=CONCAT(NOW(),'批量校验更新') "
            + " WHERE LOCATE(id, :affixIds) > 0";
        return em.createQuery(hql)
            .setParameter("status", status)
            .setParameter("affixIds", affixIds)
            .executeUpdate();
    }
    
    @Override
    @Transactional
    public void deleteAffixUpload(Date startDate, Date endDate) {
        String sql = "DELETE FROM affix_upload WHERE status = '0'"
            + " AND (create_time >= :startDate OR :startDate IS NULL)"
            + " AND (create_time < :endDate OR :endDate IS NULL)";
        em.createNativeQuery(sql)
            .setParameter("startDate", startDate)
            .setParameter("endDate", endDate)
            .executeUpdate();
        em.flush();
    }

    @Override
    @Transactional
    public void updateAffixUploadStatus(Long affixId, String status) {
        String hql = "UPDATE AffixUpload SET status = :status WHERE id = :affixId";
        em.createQuery(hql)
            .setParameter("status", status)
            .setParameter("affixId", affixId)
            .executeUpdate();
        em.flush();
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public AffixUpload getMaxOrderNoAffixUpload() {
        String hql = "FROM AffixUpload ORDER BY orderNo DESC";
        List<AffixUpload> list = em.createQuery(hql).setFirstResult(0).setMaxResults(1).getResultList();
        if(list!=null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
}
